import { Http, Headers, Response,Jsonp, RequestOptions, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/toPromise';

import { Injectable } from '@angular/core';

import { Bus } from './bus';
import { SERVER } from '../../app.config';

@Injectable()
export class BusService {
    //private bussUrl;

    constructor(
        private http: Http){
            // this.bussUrl= BUS_URL
    }

    /**
     * 功能：校验车牌编号重复 
     * 逻辑：是 返回错误信息
     *      否 返回success字段。
     */
    getMessage(bus: Bus): Promise<Bus>{
        let headers = new Headers({
            'Content-type': 'application/json'});

        return this.http.post(SERVER.BUS+'/check', JSON.stringify(bus), {headers: headers})
        .toPromise()
        .then(response => response.json() as Bus )
        .catch(this.handleError);
    }


    getBuss(): Promise<Bus[]> {
        return this.http.get(SERVER.BUS)
        .toPromise()
        .then(response => response.json() as Bus[])
        .catch(this.handleError);
    }



    getBussByCarrierID(carrier_id: string): Promise<Bus[]>{
      let headers = new Headers({
        'Content-type': 'application/json'});
      let url = `${SERVER.BUS}`+'?carrier_id='+ carrier_id;
        return this.http.get(url,{ headers: headers})
        .toPromise()
        .then(response => response.json() as Bus[])
        .catch(this.handleError);
    }

    getBus(bus_id: number) {
        return this.getBuss()
            .then(buss => buss.find(bus => bus.bus_id ===bus_id ));
    }

    private handleError(error: any): Promise<any> {
        console.error('错误：', error);

        return Promise.reject(error.message || error);
    }

    //添加
    private post(bus: Bus): Promise<string> {
        let headers = new Headers({
            'Content-type': 'application/json'});

        return this.http.post(SERVER.BUS, JSON.stringify(bus), {headers: headers})
        .toPromise()
        .then(res => res.toString())
        .catch(this.handleError);
    }

    //更新
    private put(bus: Bus): Promise<string> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.BUS}` + '/' + bus.bus_id;

        return this.http.put(url, JSON.stringify(bus), {headers: headers})
                   .toPromise()
                   .then(res => res.toString())
                   .catch(this.handleError);
    }

    //删除
    delete(bus: Bus): Promise<Response> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.BUS}/${bus.bus_id}`;

        return this.http
                   .delete(url, { headers: headers})
                   .toPromise()
                   .catch(this.handleError);
    }

    //保存
    save(bus: Bus): Promise<string> {
        if (bus.bus_id) {
            return this.put(bus)
        }
        return this.post(bus);
    }
}
